package com.fhz.day008;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileActivity extends AppCompatActivity {

    private static final String TAG = "feng";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);
    }

    public void save(View view) {
        try {
            FileOutputStream user = openFileOutput("user.txt", MODE_APPEND);
            user.write("哈哈".getBytes());
            user.flush();
            user.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void read(View view) {
        try {
            FileInputStream fileInputStream = openFileInput("user.txt");
            byte[] b = new byte[1024];
            int len = 0;
            while((len = fileInputStream.read(b)) != -1){ //1024 //512  //1
                Log.i(TAG, "onClick: "+new String(b,0,len));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveToSD(View view) {

       String[] strings =  new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        requestPermissions(strings,100);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){

            //取到当前设备的sd的存入的路径
            //当前sd的状态
            String state = Environment.getExternalStorageState();
            if(state.equals(Environment.MEDIA_MOUNTED)){
                //emulated/0
                File file = Environment.getExternalStorageDirectory();
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(file,"info.txt"));
                    fileOutputStream.write("haha".getBytes());
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}